package org.evolver.disser;

import org.apfloat.Apint;
import org.apfloat.Apfloat;
import org.apfloat.ApfloatMath;

public class DoubleParameter extends Apfloat {
    private String      myLabel;        /// Display name
    private String      myUnit;         /// Display unit
    private Integer     myDisplayPrecision;

    public DoubleParameter(
            String  label,
            String  unit,
            Double  initValue,
            Integer compPrec,
            Integer dispPrec) {
        super(initValue, compPrec);
        myLabel             = label;
        myUnit              = unit;
        myDisplayPrecision  = dispPrec;
    }

    public DoubleParameter(
            String  label,
            String  unit,
            Apfloat initValue,
            Integer compPrec,
            Integer dispPrec) {
//      TODO: revisit when apfloat.org comes back online
        super(initValue.doubleValue());
        myLabel             = label;
        myUnit              = unit;
        myDisplayPrecision  = dispPrec;
    }

    /** Rounds off the value to the desired number of decimals
     *  and returns a string.
     */
    public String getDisplayString() {
        Apfloat factor = ApfloatMath.pow(new Apfloat(10.0), myDisplayPrecision);
        Apfloat tmp = multiply(factor);
        Apfloat tmpFraction = ApfloatMath.abs(tmp.subtract(tmp.truncate()));
        tmp = tmp.truncate();
        if (tmpFraction.compareTo(new Apfloat(0.5)) != -1) {
//          Absolute value of fractional part is greater or equals 0.5
//          Add one for positive numbers and subtract one for negative ones
            tmp = tmp.add(new Apint(tmp.signum()));
        }

        return tmp.divide(factor).toString(true);
    }
    
    public String getLabel() {
        return myLabel;
    }

    public String getUnit() {
        return myUnit;
    }

    public String toString() {
        StringBuilder   result = new StringBuilder();

        result.append(myLabel);
        result.append(": ");
        result.append(getDisplayString());
        if (myUnit.length() > 0) {
            result.append(" (");
            result.append(myUnit);
            result.append(")");
        }

        return result.toString();
    }

    public static void test() {
        DoubleParameter     var1 = new DoubleParameter("var1", "unit1", 1.11, 5, 1);
        DoubleParameter     var2 = new DoubleParameter("var2", "unit2", 1.55, 5, 1);
        DoubleParameter     var3 = new DoubleParameter("var3", "unit3", -1.11, 5, 1);
        DoubleParameter     var4 = new DoubleParameter("var4", "unit4", -1.55, 5, 1);

        System.out.println(var1);
        System.out.println(var2);
        System.out.println(var3);
        System.out.println(var4);
    }
}
